﻿using UnityEngine;
using UnityEngine.UI;

// 菜单栏
public class MenuBar: MonoBehaviour {
    private GameObject mLastMenu;   // 最后添加的菜单
    private GameObject mPrefabMenu; // 预制菜单

    /**
     * 添加菜单。
     * @param title 菜单标题
     */
    public Menu Add(string title) {
        // 创建菜单
        GameObject menu = Instantiate(mPrefabMenu);
        menu.SetActive(true);
        menu.transform.SetParent(gameObject.transform);

        // 设置文字
        Text text = menu.GetComponent<Text>();
        text.text = title;

        // 设置菜单宽度，高度不变
        float width = text.fontSize * (text.text.Length + 1);
        RectTransform rectTransform = menu.GetComponent<RectTransform>();
        rectTransform.sizeDelta = new Vector2(width, rectTransform.sizeDelta.y);

        // 设置菜单位置
        if (mLastMenu == null) {
            float x = -(Screen.width - rectTransform.sizeDelta.x) / 2;
            rectTransform.anchoredPosition = new Vector2(x, 0);
        } else {
            RectTransform lastRectTransform = mLastMenu.GetComponent<RectTransform>();
            float x = lastRectTransform.anchoredPosition.x + (lastRectTransform.sizeDelta.x + rectTransform.sizeDelta.x) / 2 - 2;
            rectTransform.anchoredPosition = new Vector2(x, 0);
        }

        // 保存菜单
        mLastMenu = menu.gameObject;

        // 设置 panel 尺寸
        RectTransform panelRectTransform = menu.transform.GetComponentInChildren<RectTransform>();
        panelRectTransform.sizeDelta = rectTransform.sizeDelta;

        return mLastMenu.GetComponent<Menu>();
    }

    /**
     * 唤醒。
     */
    private void Awake() {
        // 初始化成员
        mPrefabMenu = transform.GetChild(0).gameObject;

        // 设置尺寸和位置
        RectTransform rectTransform = GetComponent<RectTransform>();
        rectTransform.sizeDelta = new Vector2(Screen.width, rectTransform.sizeDelta.y);
        float y = (Screen.height - rectTransform.sizeDelta.y) / 2;
        rectTransform.anchoredPosition = new Vector2(0, y);
    }
}
